import type { GreasyForkElements } from '../../../../../../../../../types/constants/personalization/greasy_fork'
import type { IUserData } from '../../module/script_processor/types.ts'
import { ThemeVarService } from '../../../../../../../../../lib/abstract/style/theme_var/service'
import { ICON_IDS } from '../../../../../../../../../lib/icons/types/constants'
import { PageHandler } from '../../../../../../../../../lib/page_handler'
import { GreasyForkFeedbackGroup } from '../../../../../../../../../module/page_enhancer/data_presentation/platform/greasy_fork/feedback_group'
import { GreasyForkFeedbackMark } from '../../../../../../../../../module/page_enhancer/interaction/platform/greasy_fork/feedback_mark'
import {
  AppStyleCollections,
  BodyClasses,
  PAGE_ELEMENTS,
  PROJECT_PREFIX,
  SUPPORTED_PLATFORMS,
} from '../../../../../../../../../types/constants'
import { getElementSelector } from '../../../../../../../../../types/constants/personalization/common'
import { StylesService } from '../../../../../../../../../types/constants/styles'
import { TOOLBAR_THEME_STYLE } from '../../../../common'
import { CommonPage } from '../common'

export class FeedbackPage {
  readonly name: string = 'FeedbackPage'
  elements: GreasyForkElements = PAGE_ELEMENTS[SUPPORTED_PLATFORMS.GREASY_FORK]
  private static instance: FeedbackPage
  protected readonly themeVarService: ThemeVarService = ThemeVarService.getInstance()
  private readonly stylesService: StylesService = StylesService.getInstance()
  private readonly pageHandler: PageHandler = PageHandler.getInstance()
  private readonly commonPage: CommonPage = CommonPage.getInstance()
  private readonly containerSelector = getElementSelector(this.elements, 'COMMON_CONTAINER')

  /**
   * 获取单例实例
   */
  public static getInstance(): FeedbackPage {
    if (!FeedbackPage.instance) {
      FeedbackPage.instance = new FeedbackPage()
    }
    return FeedbackPage.instance
  }

  init(): void {
    // 处理评分选项样式
    this.handleRatingLabels()

    if (this.containerSelector.length === 0)
      return

    $(`${this.containerSelector} .discussion-list-container`).each((index, element) => {
      const $element = $(element)
      const $userLink = $element.find('.discussion-meta > .discussion-meta-item > .user-link')

      // 隐藏用户链接
      $userLink.addClass(AppStyleCollections.Hide.ELEMENT)

      // 添加序号
      this.pageHandler.pages.base.addIndex(index, $element)

      // 添加用户头像
      const data: IUserData = {
        author: $userLink.text().trim(),
        authorUrl: $userLink.attr('href') || '',
      }
      this.pageHandler.features.user.addAvatar($element, data)
    })

    // 移除评分描述
    $(`${this.containerSelector} .discussion-title .rating-icon`).text('')

    // 标识注销用户（测试链接：https://greasyfork.org/zh-CN/scripts/419215-autopager/feedback）
    this.pageHandler.services.greasyFork.formatDeletedUser(`${this.containerSelector} .discussion-meta > .discussion-meta-item > i`)
  }

  /**
   * 处理评分选项样式
   */
  private handleRatingLabels(): void {
    const RATING_LABELS = {
      neutral: '不评分',
      bad: '差评',
      ok: '一般',
      good: '好评',
    }

    const RATING_CLASS_MAP: Record<string, string> = {
      [RATING_LABELS.neutral]: 'rating-icon-neutral',
      [RATING_LABELS.bad]: 'rating-icon-bad',
      [RATING_LABELS.ok]: 'rating-icon-ok',
      [RATING_LABELS.good]: 'rating-icon-good',
    }

    $('.post-discussion .discussion-rating .radio-label').each((_, element) => {
      const $label = $(element)
      const labelText = $label.text().trim()

      // 匹配关键词并添加对应类
      Object.entries(RATING_CLASS_MAP).forEach(([keyword, className]) => {
        if (labelText.includes(keyword)) {
          $label.addClass(className)
        }
      })
    })

    // 监听选择变化
    $('.post-discussion .discussion-rating input[type="radio"]').on('change', function () {
      // 移除所有高亮
      $('.radio-label').removeClass('rating-selected')

      // 为选中项添加高亮
      $(this).next('.radio-label').addClass('rating-selected')
    })
  }

  getMainStyles(): string {
    if (this.containerSelector.length === 0)
      return ''

    return `
${this.containerSelector} {
  #script-content {    
    /* 月份分割符 */
    .script-discussion-list {
      ${GreasyForkFeedbackGroup.styles()}
    }
    
    /* 发布讨论 */
    .post-discussion {
      #new-script-discussion {
        .comment-screenshot-control {
          display: flex;
          flex-direction: column;
          gap: 10px;
          
          input[type="file"].${BodyClasses.FILE_UPLOADED} {
            color: var(${this.themeVarService.link.default.text}) !important;
          }
        }
        
        .discussion-rating {
          .radio-label {
            background-color: unset !important;
            
            &::before {
              ${this.stylesService.inlinePseudo.icon()}
            }
            
            &.rating-selected {
              position: relative;
              font-weight: 600;
              letter-spacing: 0.5px;
            }
            
            &.rating-icon-neutral {
              color: var(--${PROJECT_PREFIX}-theme-text-secondary) !important;
              
              &::before {
                background-image: var(${this.themeVarService.generateIcon(ICON_IDS.rating.unrated)}) !important;
              }
            }
            &.rating-icon-bad {
              color: var(--${PROJECT_PREFIX}-theme-danger-text) !important;
              
              &::before {
                background-image: var(${this.themeVarService.generateIcon(ICON_IDS.rating.bad)}) !important;
              }
            }
            &.rating-icon-ok {
              color: var(--${PROJECT_PREFIX}-theme-warning-text) !important;
              
              &::before {
                background-image: var(${this.themeVarService.generateIcon(ICON_IDS.rating.ok)}) !important;
              }
            }
            &.rating-icon-good {
              color: var(--${PROJECT_PREFIX}-theme-success-text) !important;
              
              &::before {
                background-image: var(${this.themeVarService.generateIcon(ICON_IDS.rating.good)}) !important;
              }
            }
          }
        }
      }
    }

    /* 结果列表 */
    .discussion-list-container {
      grid-template-columns: auto 1fr;
      grid-template-rows: auto auto; /* 行数 */
      grid-template-areas:
        "index index"
        "avatar article";
      background: var(${this.themeVarService.default.background.list}) !important;
      ${this.commonPage.baseListStyles()}
      ${this.commonPage.highlightFeedbackResultStyle()}
      
      /* 内容区域 */
      .discussion-list-item {
        grid-area: article;
        min-width: 0; /* 防止内容溢出 */
        border: none !important;
      }
    }
    
    /* 标签 */
    ${GreasyForkFeedbackMark.getTagStyles()}
    
    /* 讨论列表 */
    .script-discussion-list .discussion-list-item {
      /* 工具栏 */
      ${TOOLBAR_THEME_STYLE}
      
      /* 用户链接 */
      .user-link {
        ${this.stylesService.link.default()}
      }
      
      /* 元数据 */
      .discussion-meta {
        display: flex !important;
        align-items: center !important;
        
        .discussion-meta-item  {
          color: var(--${PROJECT_PREFIX}-theme-text-secondary) !important;
          
          /* 时间 */
          relative-time {
            color: var(--${PROJECT_PREFIX}-theme-text-secondary) !important;
          }
          
          /* 精确时间 */
          .gf-time-helper {
            white-space: nowrap !important;
          }
          
          .discussion-meta-item {
            display: flex !important;
            align-items: center !important;
            justify-content: flex-end !important;
            gap: 5px !important;
            white-space: nowrap !important;
            
            .badge {
              margin-left: 0 !important;
            }
            
            .gf-time-helper {
              margin-left: -5px;
            }
          }
        }
      }
      
      .discussion-meta > .discussion-meta-item {
        display: flex;
        align-items: center;
        gap: 5px;
        
        & > i {
          display: contents;
          .deleted-user-wrapper {
            display: contents;
          }
        }
      }
    }
  }
}
`
  }
}
